package com.ukao.steward.ui.valetRunners.toShop;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.github.jdsjlzx.ItemDecoration.DividerDecoration;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.ukao.steward.R;
import com.ukao.steward.adapter.BatchGoodsAllAdapter;
import com.ukao.steward.adapter.BatchGoodsAlreadyToShopAdapter;
import com.ukao.steward.adapter.BatchGoodsNotToShopAdapter;
import com.ukao.steward.adapter.OrderGoodsAllAdapter;
import com.ukao.steward.adapter.OrderGoodsAlreadyToShopAdapter;
import com.ukao.steward.adapter.OrderNotToShopAdapter;
import com.ukao.steward.base.MvpFragment;
import com.ukao.steward.bean.BatchClothingBean;
import com.ukao.steward.bean.OrderClothingBean;
import com.ukao.steward.consts.Constant;
import com.ukao.steward.pesenter.valetRunners.GoodsToShopDetailsPresenter;
import com.ukao.steward.util.ActivityUtils;
import com.ukao.steward.util.CheckUtils;
import com.ukao.steward.util.T;
import com.ukao.steward.view.valetRunners.GoodsToShopDetailsView;
import com.ukao.steward.widget.ClearEditText;
import com.ukao.steward.widget.MyLRecyclerView;
import com.ukao.steward.widget.StateButton;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 商品到店详情
 */
public class GoodsToShopDetailsFragment extends MvpFragment<GoodsToShopDetailsPresenter> implements GoodsToShopDetailsView {

    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "tabColumn";
    private static final String ARG_PARAM2 = "id";
    private static final String ARG_PARAM3 = "dataLoadMode";

    private int mColumnCount;  //tab 位置
    private int mDataLoadMode;  //数据加载方式
    private String oddNumbersId;
    private Unbinder unbinder;
    private OnFragmentInteractionListener mListener;
    private BatchGoodsAllAdapter batchGoodsAllAdapter;    //全部商品
    private BatchGoodsNotToShopAdapter batchGoodsNotToShopAdapter;  //未到店的适配器
    private BatchGoodsAlreadyToShopAdapter batchGoodsAlreadyToShopAdapter;  //已经到店

    private OrderGoodsAllAdapter orderGoodsAllAdapter;
    private OrderGoodsAlreadyToShopAdapter orderGoodsAlreadyToShopAdapter;
    private OrderNotToShopAdapter orderNotToShopAdapter;

    private LRecyclerViewAdapter mLRecyclerViewAdapter;
    private List<BatchClothingBean> mBatchData;  //list 集合
    private List<OrderClothingBean> mOrderData;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottomLayout;
    @BindView(R.id.lrecycler_view)
    MyLRecyclerView mRecyclerViewList;
    @BindView(R.id.all_to_shop_btn)
    StateButton sbAllToShop;
    @BindView(R.id.confirm_btn)
    StateButton searchBtn;
    @BindView(R.id.edit_text)
    ClearEditText etInputText;
    @BindView(R.id.sweep_image)
    ImageView ivSweepImg;   //扫码
    @BindView(R.id.fl_root)   //跟布局
            LinearLayout mRootLayout;
    private boolean isVisibleRefresh=true;  //是否加载结束

    public GoodsToShopDetailsFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment GoodsToShopDetailsFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static GoodsToShopDetailsFragment newInstance(int columnCount, String idCode, int dataLoadMode) {
        GoodsToShopDetailsFragment fragment = new GoodsToShopDetailsFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, columnCount);
        args.putString(ARG_PARAM2, idCode);
        args.putInt(ARG_PARAM3, dataLoadMode);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mColumnCount = getArguments().getInt(ARG_PARAM1, 0);
            oddNumbersId = getArguments().getString(ARG_PARAM2, "");
            mDataLoadMode = getArguments().getInt(ARG_PARAM3, 100);
        }
    }

    @Override
    protected GoodsToShopDetailsPresenter createPresenter() {
        return new GoodsToShopDetailsPresenter(this);  //传送对方的接口
    }

    @Override
    protected void initView() {
        if (mColumnCount != 1) {
            llBottomLayout.setVisibility(View.GONE);
        }
        switch (mDataLoadMode) {
            case ToShopFragment.BATCH_TO_SHOP_FLAG:
                mBatchData = new ArrayList<>();
                break;
            case ToShopFragment.ORDER_TO_SHOP_FLAG:
                mOrderData = new ArrayList<>();
                break;
        }
        initLinearRecyclerView(mRecyclerViewList);
        initAdapter();

    }


    //初始化适配器
    private void initAdapter() {
        switch (mDataLoadMode) {
            case ToShopFragment.BATCH_TO_SHOP_FLAG:
                switch (mColumnCount) {
                    case 1:  //共多少件
                        batchGoodsAllAdapter = new BatchGoodsAllAdapter(getActivity(), mBatchData);
                        mLRecyclerViewAdapter = new LRecyclerViewAdapter(batchGoodsAllAdapter);
                        break;
                    case 2://已到店
                        batchGoodsAlreadyToShopAdapter = new BatchGoodsAlreadyToShopAdapter(getActivity(), mBatchData);
                        mLRecyclerViewAdapter = new LRecyclerViewAdapter(batchGoodsAlreadyToShopAdapter);
                        break;
                    case 3: //未到店
                        batchGoodsNotToShopAdapter = new BatchGoodsNotToShopAdapter(getActivity(), mBatchData);
                        mLRecyclerViewAdapter = new LRecyclerViewAdapter(batchGoodsNotToShopAdapter);
                        break;
                }
                break;
            case ToShopFragment.ORDER_TO_SHOP_FLAG:
                switch (mColumnCount) {
                    case 1:  //共多少件
                        orderGoodsAllAdapter = new OrderGoodsAllAdapter(getActivity(), mOrderData);
                        mLRecyclerViewAdapter = new LRecyclerViewAdapter(orderGoodsAllAdapter);
                        break;
                    case 2://已到店
                        orderGoodsAlreadyToShopAdapter = new OrderGoodsAlreadyToShopAdapter(getActivity(), mOrderData);
                        mLRecyclerViewAdapter = new LRecyclerViewAdapter(orderGoodsAlreadyToShopAdapter);
                        break;
                    case 3: //未到店
                        orderNotToShopAdapter = new OrderNotToShopAdapter(getActivity(), mOrderData);
                        mLRecyclerViewAdapter = new LRecyclerViewAdapter(orderNotToShopAdapter);
                        break;
                }
                break;
        }
        mRecyclerViewList.setAdapter(mLRecyclerViewAdapter);
        DividerDecoration dividerDecoration = new DividerDecoration.Builder(getActivity())
                .setHeight(R.dimen.horizontal_divider_height)  //设置分割线的高度
                .setColor(Color.parseColor("#c6c6c6"))  //设置分割线的颜色
                .build();
        mRecyclerViewList.addItemDecoration(dividerDecoration);
        mRecyclerViewList.setLoadMoreEnabled(false);
    }

    @Override
    protected void initListener() {
        mRecyclerViewList.setOnRefreshListener(mOnRefreshListener);  //监听刷新
//        mRootLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
//            @Override
//            public void onGlobalLayout() {
//                Rect r = new Rect();
//                mRootLayout.getWindowVisibleDisplayFrame(r);
//                //获得屏幕整体的高度
//                int screenHeight = mRootLayout.getRootView().getHeight();
//
//                int softHeight = screenHeight - r.bottom ;
//                //不可见区域大于屏幕本身高度的1/4：说明键盘弹起了
//                 if(softHeight>screenHeight/4){
//                     int[] location = new int[2];
//                     llBottomLayout.getLocationInWindow(location);
//                     // 4､获取Scroll的窗体坐标，算出main需要滚动的高度
//                     int srollHeight = (location[1] + llBottomLayout.getHeight()) - r.bottom;
//                     //5､让界面整体上移键盘的高度
//                     mRootLayout.scrollTo(0, srollHeight);
//                 }else {
//                     mRootLayout.scrollTo(0, 0);
//                 }
//            }
//        });
    }

    /**
     * 刷新接口
     */
    private OnRefreshListener mOnRefreshListener = new OnRefreshListener() {
        @Override
        public void onRefresh() {
            cleanData();
            mLRecyclerViewAdapter.notifyDataSetChanged();  //刷新适配器
            //网络请求数据
            switch (mDataLoadMode) {
                case ToShopFragment.BATCH_TO_SHOP_FLAG:
                    mvpPresenter.onColumnRequestBatchData(mColumnCount, oddNumbersId);
                    break;
                case ToShopFragment.ORDER_TO_SHOP_FLAG:
                    mvpPresenter.onColumnRequestOrderData(mColumnCount, oddNumbersId);
                    break;
            }
        }
    };

    private void cleanData() {
        switch (mDataLoadMode) {
            case ToShopFragment.BATCH_TO_SHOP_FLAG:
                switch (mColumnCount) {
                    case 1:
                        batchGoodsAllAdapter.getDataList().clear();
                        break;
                    case 2:
                        batchGoodsAlreadyToShopAdapter.getDataList().clear();
                        break;
                    case 3:
                        batchGoodsNotToShopAdapter.getDataList().clear();
                        break;
                }
                break;
            case ToShopFragment.ORDER_TO_SHOP_FLAG:
                switch (mColumnCount) {
                    case 1:
                        orderGoodsAllAdapter.getDataList().clear();
                        break;
                    case 2:
                        orderGoodsAlreadyToShopAdapter.getDataList().clear();
                        break;
                    case 3:
                        orderNotToShopAdapter.getDataList().clear();
                        break;
                }
                break;
        }
    }

    @OnClick({R.id.all_to_shop_btn, R.id.confirm_btn, R.id.sweep_image})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.all_to_shop_btn:  //全部到店
                mvpPresenter.onRequestClothingGoodsReceiving(mDataLoadMode, oddNumbersId);
                break;
            case R.id.confirm_btn:
                traversalClothingCode(etInputText);
                break;
            case R.id.sweep_image:   //扫码
                Intent mIntent = ActivityUtils.JumpToBundleActivity(_mActivity);
                startActivityForResult(mIntent, Constant.REQUEST_CODE);
                break;
        }
    }

    /**
     * 遍历衣物条码
     */
    private void traversalClothingCode(ClearEditText etInputText) {
        String str = getText(etInputText);
        if (!CheckUtils.isEmpty(str)) {
            String id = "";
            boolean isExist = false;
            if (mDataLoadMode == ToShopFragment.BATCH_TO_SHOP_FLAG) {  //批次
                mBatchData = batchGoodsAllAdapter.getDataList();
                for (BatchClothingBean mBatchBean : mBatchData) {
                    //判断数据的条码是否存在
                    if (mBatchBean.getScanCode().equals(str)) {
                        if (mBatchBean.getStoreStatusText().equals("已核对")) {
                            T.show("该衣物门店已确认");
                            return;
                        } else {
                            isExist = true;
                            id = String.valueOf(mBatchBean.getId());
                            break;
                        }
                    }
                }
            } else {   //订单
                mOrderData = orderGoodsAllAdapter.getDataList();
                for (OrderClothingBean mOrderBean : mOrderData) {
                    if (mOrderBean.getScanCode().equals(str)) {
                        if (mOrderBean.getIsStoreStatus() == 1) {
                            T.show("该衣物门店已确认");
                            return;
                        } else {
                            isExist = true;
                            id = String.valueOf(mOrderBean.getId());
                            break;
                        }
                    }
                }
            }
            if (isExist && !TextUtils.isEmpty(id)) {
                isVisibleRefresh =false;
                mvpPresenter.onRequestSingleClothingGoodsReceiving(mDataLoadMode, oddNumbersId, id);
            } else {
                T.show("衣物条码不存在!");
            }
        } else {
            T.show("请输入正确的订单号/运单号");
        }
    }

    @Override
    public void onSupportVisible() {   //可见的
        super.onSupportVisible();
        Log.d("1111", "onRefresh: ");

        if (isVisibleRefresh)
            mRecyclerViewList.forceToRefresh();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == _mActivity.RESULT_OK) {
            switch (requestCode) {
                case Constant.REQUEST_CODE:
                    String code = data.getStringExtra(Constant.ARG_PARAM1);
                    etInputText.setText(code);
                    etInputText.setSelection(code.length());
                    traversalClothingCode(etInputText);
                    break;
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_goods_to_shop_details, container, false);
        //绑定
        unbinder = ButterKnife.bind(this, view);
        initView();
        initListener();
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
//        if (context instanceof OnFragmentInteractionListener) {
//            mListener = (OnFragmentInteractionListener) context;
//        } else {
//            throw new RuntimeException(context.toString()
//                    + " must implement OnFragmentInteractionListener");
//        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //解绑
        unbinder.unbind();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onReceivingBatchDataSucceed(List<BatchClothingBean> list) {
        int NotToShopCount = 0;
        int toShopCount = 0;
        switch (mColumnCount) {
            case 1:
                batchGoodsAllAdapter.setDataList(list);
                for (BatchClothingBean bean : list) {
                    if (bean.getStoreStatus() == 0) {  //未核对
                        NotToShopCount++;
                    } else if (bean.getStoreStatus() == 1) {   //已核对
                        toShopCount++;
                    }
                }
                //获得父布局 改变tab  UI
                ((ToShopCheckFragment) (this.getParentFragment())).changeTabLayout(list.size(), toShopCount, NotToShopCount);
                break;
            case 2:
                batchGoodsAlreadyToShopAdapter.setDataList(list);
                break;
            case 3:
                batchGoodsNotToShopAdapter.setDataList(list);
                break;
        }
    }

    @Override
    public void onReceivingOrderDataSucceed(List<OrderClothingBean> list) {
        int NotToShopCount = 0;
        int toShopCount = 0;
        switch (mColumnCount) {
            case 1:
                orderGoodsAllAdapter.setDataList(list);
                for (OrderClothingBean bean : list) {
                    if (bean.getIsStoreStatus() == 0) {  //未到店
                        NotToShopCount++;
                    } else if (bean.getIsStoreStatus() == 1) {   //已到店
                        toShopCount++;
                    }
                }
                //获得父布局 改变tab  UI
                ((ToShopCheckFragment) (this.getParentFragment())).changeTabLayout(list.size(), toShopCount, NotToShopCount);
                break;
            case 2:
                orderGoodsAlreadyToShopAdapter.setDataList(list);
                break;
            case 3:
                orderNotToShopAdapter.setDataList(list);
                break;
        }

    }


    /**
     * 刷新数据
     */

    @Override
    public void onRefreshData() {
        mRecyclerViewList.forceToRefresh();
    }


    /**
     * 刷新结束
     */
    @Override
    public void onLoadFinish() {
        mRecyclerViewList.refreshFinish();
        isVisibleRefresh =true;
    }

    /**
     * 请求失败
     */
    @Override
    public void onRequestFailed() {
        isVisibleRefresh =true;
    }


    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
